package com.jinxin.platform.cdacsrecord.core.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Description: bccah
 * Created by 34759 on 2019/8/16 17:33
 */
@Component
public class UploadFileUtil {
    private final static Logger logger = LoggerFactory.getLogger(UploadFileUtil.class);

    public static String getFileNameByTime(MultipartFile file){
        DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateStr = format.format(new Date());
        if(file != null){
            String originalName = file.getOriginalFilename();
            String prefix = originalName.substring(originalName.lastIndexOf(".")+1);
            return dateStr + "." + prefix;
        }
        return dateStr;
    }

    public static String uploadFile(MultipartFile file, String secondPath, String realPath ){
        String accessDir = "/static/"+secondPath+"/";
        String prefix = "";
        String dateStr = "";
        //保存上传
        OutputStream out = null;
        InputStream fileInput=null;
        DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        try{
            if(file!=null){
                dateStr = format.format(new Date());
                String originalName = file.getOriginalFilename();
                prefix=originalName.substring(originalName.lastIndexOf(".")+1);
                String filepath = realPath + accessDir + dateStr + "." + prefix;
                filepath = filepath.replace("\\", "/");
                File files=new File(filepath);
                //打印查看上传路径
                System.out.println(filepath);
                logger.info(filepath);
                if(!files.getParentFile().exists()){
                    files.getParentFile().mkdirs();
                }
                file.transferTo(files);
                return accessDir + dateStr + "." + prefix;
            }
        }catch (Exception e){
        }finally{
            try {
                if(out!=null){
                    out.close();
                }
                if(fileInput!=null){
                    fileInput.close();
                }
            } catch (IOException e) {
            }
        }
        return null;
    }

    public static String downFile(String realPath, String fileName , HttpServletResponse response ){
        File file = new File(realPath, fileName);
        logger.info("down file:"+file);
        if (file.exists()) {
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.addHeader("Content-Disposition",
                    "attachment;fileName=" +  fileName);// 设置文件名
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                System.out.println("success");
            } catch (Exception e) {
                logger.error("error",e);
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        logger.error("error",e);
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        logger.error("error",e);
                    }
                }
            }
        }else{
            logger.error( file + "文件不存在");
        }
        return null;
    }
    public static String getRealPath() {
        String realPath = "";  // 获取保存的路径，本地磁盘中的一个文件夹
        if (OSinfo.isWindows()) {
            realPath = "d://uploadFiles/";
        } else if (OSinfo.isLinux()) {
            realPath = "/data/uploadFiles/";
        }
        return realPath;
    }

    public static File multipartFileToFile(MultipartFile multiFile) {
        // 获取文件名
        String fileName = multiFile.getOriginalFilename();
        // 获取文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        fileName = fileName.substring(0,fileName.lastIndexOf("."));
        // 若需要防止生成的临时文件重复,可以在文件名后添加随机码
        try {
            File file = File.createTempFile(fileName, suffix);
            multiFile.transferTo(file);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
